import time

import allure
import yaml
from selenium.webdriver.common.by import By

from cloud_po.pages.base_page import BasePage
from cloud_po.utils.log_utils import logger


class LoginPage(BasePage):
    _BASE_URL = "http://wxorder.taover.com/login?redirect=%2Fdashboard"
    __INPUT_USERNAME = (By.NAME, "username")
    __INPUT_PASSWORD = (By.NAME, "password")
    __CAPTCHA = (By.ID, "s-canvas")
    __INPUT_CAPTCHA = (By.CSS_SELECTOR, "[placeholder='请输入验证码']")
    __LOGIN_BTN = (By.XPATH, "//span[text()='登录']")

    def login(self):
        """登录页面"""
        logger.info("进入登录页面")

        with allure.step("输入用户名密码"):
            self.do_send_keys("17611219803", self.__INPUT_USERNAME)
            self.do_send_keys("Ceba_17611219803", self.__INPUT_PASSWORD)
        with allure.step("输入验证码"):
            # 手动输入验证码
            time.sleep(10)
        with allure.step("点击登录按钮"):
            self.do_find(self.__LOGIN_BTN).click()
    #
        self.get_cookie()
        self.login_by_cookie()

        logger.info("返回首页")
        from cloud_po.pages.home_page import HomePage
        return HomePage(self.driver)

    def get_cookie(self):
        time.sleep(30)
        cookies = self.driver.get_cookies()
        with open("./data/cookies.yaml", "w", encoding="utf-8") as f:
            yaml.safe_dump(cookies, f)

    def login_by_cookie(self):
        cookies = yaml.safe_load(open("./data/cookies.yaml", "r"))
        for cookie in cookies:
            self.driver.add_cookie(cookie)
        self.driver.refresh()
